import { getAdminSimpleInfo } from "@/views/superAdmin/admin/api";
import { removeAdminToken } from "@/utils/auth";
import routerUtil from "@/router/routerUtil";
import { isNull } from "@/utils/service";

const user = {
  state: {
    id: 0,
    nickname: "",
    avatar: "",
    account: "",
    roles: [],
    permissions: [],
    routeList: [],
  },
  mutations: {
    SET_ID: (state, id) => {
      state.id = id;
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account;
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_ROUTE_LIST: (state, routes) => {
      state.routeList = routes
    }
  },
  actions: {
    GetInfo: function({ commit, state }) {
      return new Promise((resolve, reject) => {
        getAdminSimpleInfo().then(r => {
          commit("SET_ID", r.adId || 0);
          commit("SET_ACCOUNT", r.account || "");
          commit("SET_NICKNAME", r.name || "");
          commit("SET_ROLES", !isNull(r.roleNames) ?  r.roleNames : [undefined]);
          commit("SET_PERMISSIONS", !isNull(r.permissions) ? r.permissions : [undefined]);
          commit("SET_ROUTE_LIST", !isNull(r.routeList) ? r.routeList : [undefined]);
          // 动态路由初始化
          routerUtil.init();
          resolve(r);
        }).catch(err => {
          reject(err);
        });
      });
    },
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit("SET_ROLES", []);
        commit("SET_PERMISSIONS", []);
        removeAdminToken();
        resolve()
      });
    },
  }
};


export default user;